#!/usr/bin/python
#  Copyright (c) 2012 njjs Inc. All rights reserved.
#  Author : bianxiongfeng.
import sys,os,string
from datetime import date



'''
Config :
'''
Config={
    "Company":"YFinder.Net",
	"Author":"bianxiongfeng",
	"Email":"cinience@gmail.com  cinience@qq.com",
	"WorkSpace":"YFinder",
	"TmpFile":".TmpFile__"
}


   

def writeHead(headcontext):
	today=date.today()
	f.writelines("/* \n* Copyright (c) 2012 "+Config["Company"]+" Inc. All rights reserved.\n")
	f.writelines("* Author : "+Config["Author"]+"\n")
	f.writelines("* Brief  : \n* Histroy: create "+str(today.year)+"-"+str(today.month)+"-"+str(today.day) + "\n*/\n\n")
	f.writelines("#ifndef "+headcontext+"//NOLINT"+"\n")
	f.writelines("#define "+headcontext+"//NOLINT"+"\n\n")

def copyFile(sfile,defile):
	f1=open(sfile,'r')
	f2=open(defile,'w+')
	f2.write(f1.read())
	f1.close()
	f2.close()

def hasStr(dstr,fstr):
    return fstr in dstr





def handleMacro(filename):
	headcontext = filename
	headcontext = headcontext+'_'
	headcontext=string.upper(headcontext)
	print(headcontext)
	pos=headcontext.find(Config["WorkSpace"]);
	if pos != -1:
	    headcontext=headcontext[pos:]
	headcontext=string.replace(headcontext,':','_')
	headcontext=string.replace(headcontext,'\\','_')
	headcontext=string.replace(headcontext,'/','_')
	headcontext=string.replace(headcontext,'.','__')
	headcontext='_'+headcontext
	print(headcontext)
	return headcontext


def copyMainContent():
	ftmp = open(Config["TmpFile"],'r')
	f = open(filename,'w+')
	flag=0
	for line in ftmp:
		if (hasStr(line,"#ifndef") or hasStr(line,"#define")) and (hasStr(line,"_h_") or hasStr(line,"_H_")):
			print(" * *find "+line)
			flag=1
		elif (hasStr(line,"* Copyright")) or (hasStr(line,"* Author")) or hasStr(line,"* Brief")  or hasStr(line,"* Histroy") :
		    continue
		elif hasStr(line,"#pragma") and hasStr(line,"once"):
			print(" * find "+line)
		else:	
		    f.writelines(line)
		    print("   add "+line)

	if flag == 0:
	    f.write("\n#endif //"+headcontext+"//NOLINT\n")
	else :
		tmp="//"+headcontext+"//NOLINT"
		tmpfile=open(filename,"r")
		if not (hasStr(tmpfile.read(),tmp)):
		    f.write("//"+headcontext+"//NOLINT")
		tmpfile.close()
	f.close()
	ftmp.close()
	os.remove(Config["TmpFile"])

def main():
	filename=sys.argv[1]
    macro=handleMacro(filename)
    copyFile(filename,Config["TmpFile"])
    writeHead(macro)
    copyMainContent()



if __name__ == '__main__':
	main()




